/*
 * Powered By fanrenqij.com
 * Since 2017 - 2017
 */

package com.fanrenqiji.modules.business.teacher.web;


import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.persistence.Page;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.business.teacher.service.TeacherService;
import com.fanrenqiji.modules.business.teacher.vo.TeacherVO;
import com.fanrenqiji.modules.business.wechatuser.service.WeChatUserService;
import com.fanrenqiji.modules.business.wechatuser.vo.WeChatUserVO;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/business/teacher")
public class TeacherController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(TeacherController.class);
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private WeChatUserService weChatUserService;
    @Autowired
    private WxMpService wxService;

    @ModelAttribute("teacher")
    public TeacherVO getTeacher(@RequestParam(required = false) String id) {
        if (StringUtils.isNotEmpty(id)) {
            return teacherService.get(id);
        } else {
            return new TeacherVO();
        }
    }

    /**
     * 列表
     *
     * @return
     */
    @RequiresPermissions("business:teacher:view")
    @RequestMapping(value = {"list", ""})
    public String list(TeacherVO teacher, HttpServletRequest request, HttpServletResponse response, Model model) {
//        teacher.setCompanyId(UserUtils.getUser().getOffice().getId().toString());
        Page<TeacherVO> page = teacherService.findTeacherByPage(new Page<TeacherVO>(request, response), teacher);

        model.addAttribute("page", page);
        model.addAttribute("teacher", teacher);
        return "modules/business/teacher/teacherList";
    }


    /**
     * 选择列表
     *
     * @return
     */
    @RequestMapping(value = "select")
    public String select(TeacherVO teacher, HttpServletRequest request,HttpServletResponse response, Model model) {
        Page<TeacherVO> page = teacherService.findTeacherByPage(new Page<TeacherVO>(request, response,10),teacher);
        model.addAttribute("page", page);
        model.addAttribute("teacher", teacher);
        return "modules/business/teacher/teacherSelect";
    }

    /**
     * 用户添加更新表
     *
     * @param model
     * @return
     */
    @RequiresPermissions("business:teacher:view")
    @RequestMapping(value = "form")
    public String form(Model model, TeacherVO teacher) {
        if (StringUtils.isNotEmpty(teacher.getId())) {
            model.addAttribute("teacher", teacherService.get(teacher.getId()));
        } else {
            model.addAttribute("teacher", teacher);
        }
        return "modules/business/teacher/teacherForm";
    }

    /**
     * 添加或修改提交
     *
     * @param teacher
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("business:teacher:edit")
    @RequestMapping(value = "save")
    public String save(TeacherVO teacher, Model model, RedirectAttributes redirectAttributes) {// TODO @Valid 添加后端校验
        teacher.setCompanyId(teacher.getOffice().getId().toString());
        if (!beanValidator(model, teacher)) {
            return form(model, teacher);
        }
        try{
            teacher = teacherService.update(teacher);
        }catch (Exception e){
            model.addAttribute("message", "保存失败！请检查信息填写是否有问题");
            model.addAttribute("teacher", teacher);
            return "modules/business/teacher/teacherForm";
        }
        //修改菜单
        if ("1".equals(teacher.getStatus())){
            WeChatUserVO weChatUser = teacher.getWeChatUser();
            if (weChatUser !=null && StringUtils.isNotBlank(weChatUser.getOpenId()))
                try {
                    wxService.getUserTagService().batchTagging(105l, new String[]{weChatUser.getOpenId()});
                    weChatUser.setGroupId("105");
                    weChatUserService.update(weChatUser);
                } catch (WxErrorException e) {
                    addMessage(redirectAttributes, "保存成功");
                    return "redirect:" + GlobalSetting.getAdminPath() + "/business/teacher/";
                }
        }
        addMessage(redirectAttributes, "保存成功");
        return "redirect:" + GlobalSetting.getAdminPath() + "/business/teacher/";
    }

    /**
     * 删除操作
     *
     * @return
     */
    @RequestMapping("delete")
    @RequiresPermissions("business:teacher:edit")
    public String delete(String id, RedirectAttributes redirectAttributes) {
        teacherService.delete(id);
        addMessage(redirectAttributes, "删除成功");
        return "redirect:" + GlobalSetting.getAdminPath() + "/business/teacher/";
    }

    /**
     * 放大镜 teacher All
     */
    @ResponseBody
    @RequestMapping(value = "all")
    public List<Map<String, Object>> all(HttpServletResponse response){
        response.setContentType("application/json; charset=UTF-8");
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<TeacherVO> list = teacherService.getAll();
        for(int i=0;i<list.size();i++){
            TeacherVO teacherVO = list.get(i);
            if (teacherVO!=null){
                Map<String, Object> map = Maps.newHashMap();
                map.put("id",teacherVO.getId());
                map.put("name",teacherVO.getName());
                mapList.add(map);
            }
        }
        return mapList;
    }
    /**
     * 查看下级教师列表
     *
     * @return
     */
    @RequiresPermissions("business:teacher:view")
    @RequestMapping("subsidiaryList")
    public String subsidiaryList(TeacherVO teacher, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<TeacherVO> page = teacherService.findTeacherByPage(new Page<TeacherVO>(request, response), teacher);
        model.addAttribute("page", page);
        model.addAttribute("teacher", teacher);
        return "modules/business/teacher/subsidiaryList";
    }
    /**
     * 选择列表2
     *
     * @return
     */
    @RequestMapping(value = "select2")
    public String select2(TeacherVO teacher, HttpServletRequest request,HttpServletResponse response, Model model) {
        Page<TeacherVO> page = teacherService.findTeacherByPage2(new Page<TeacherVO>(request, response,10),teacher);
        model.addAttribute("page", page);
        model.addAttribute("teacher", teacher);
        return "modules/business/teacher/teacherSelect2";
    }
}